<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<input type="file" onchange="aaa()" id="file">
<script>
  function aaa() {
    console.log(document.getElementById('file').files[0])
    let imgFile = document.getElementById('file').files[0];
    let reader = new FileReader();
    reader.readAsDataURL(imgFile);
    reader.onload = function (e) {
      let image = new Image();
      image.src = e.target.result;
      image.onload = function () {
        let size;
        if(imgFile.size/1024/1024 > 20){
          size = 20;
        }else if(imgFile.size/1024/1024 > 10){
          size = 10;
        }else if(imgFile.size/1024/1024 > 5 && imgFile.size/1024/1024 < 10){
          size = 5;
        }else{
          size = 1;
        }
        console.log(image.width)
        console.log(image.height)
        let canvas = document.createElement('canvas'),
          context = canvas.getContext('2d'),
          imageWidth = image.width/size,
          imageHeight = image.height/size,
          data = '';
        canvas.width = imageWidth;
        canvas.height = imageHeight;

        context.drawImage(image,0,0,imageWidth,imageHeight);
        data = canvas.toDataURL('image/png');

        console.log(data);
        console.log(dataURLtoFile(data,imgFile.name))
      }
    }
  }
  //base64 转 File
  function dataURLtoFile(dataurl, filename) {//将base64转换为文件
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
  }



  /*  let reader = new FileReader();
    reader.readAsDataURL(imgFile);
    reader.onload = function (e) {
      let image = new Image();
      image.src = e.target.result;
      image.onload = function () {
        let canvas = document.createElement('canvas'),
          context = canvas.getContext('2d'),
          imageWidth = image.width / 2,
          imageHeight = image.height / 2,
          data = '';

        canvas.width = imageWidth;
        canvas.height = imageHeight;

        context.drawImage(image,0,0,imageWidth,imageHeight);
        data = canvas.toDataURL('image/png');

        console.log(data);
      }
    }

    return false;*/
</script>
</body>
</html>
